package com.yanqu.road.server.gameplayer.module.player;

import com.yanqu.road.entity.player.UserRealReward;
import com.yanqu.road.logic.bussiness.player.UserRealRewardBusiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.pb.activity.LuckyDrawProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.pb.LuckyDrawPb;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

public class RealRewardModule extends GeneralModule {

    private List<UserRealReward> userRealRewardList = new ArrayList<>();

    public RealRewardModule(GamePlayer player) {
        super(player);
    }

    /**
     * 获取未过期的实物奖励
     */
    public List<UserRealReward> getNoExpireUserRealRewardList() {
        List<UserRealReward> list = new ArrayList<>(userRealRewardList);

        List<UserRealReward> noExpireList = new ArrayList<>();

        long expireGetTime = System.currentTimeMillis() - GameConfig.REAL_REWARD_EXPIRE_TIME * DateHelper.HOUR_MILLIONS;
        for (int i = list.size() - 1; i >= 0; i--) {
            UserRealReward userRealReward = list.get(i);
            if (userRealReward.getGetTime().getTime() > expireGetTime) {
                noExpireList.add(userRealReward);
            } else {
                break;
            }
        }
        Collections.reverse(noExpireList);

        return noExpireList;
    }

    /**
     * 添加实物奖励
     */
    public void addRealReward(int goodsId, long num) {
        log.debug("user {} add real reward goodsId {} num {}.", getUserId(), goodsId, num);

        synchronized (userRealRewardList) {
            int maxNo = userRealRewardList.isEmpty() ? 0 : userRealRewardList.get(userRealRewardList.size() - 1).getNo();
            for (int i = 0; i < num; i++) {
                UserRealReward userRealReward = new UserRealReward();
                userRealReward.setUserId(getUserId());
                userRealReward.setNo(++maxNo);
                userRealReward.setGoodsId(goodsId);
                userRealReward.setGetTime(new Date());
                userRealReward.setAddrTime(new Date(0));
                userRealReward.setAddr("");
                userRealReward.setPhone("");
                userRealReward.setInsertOption();
                userRealRewardList.add(userRealReward);
            }
        }
    }

    /**
     * 填写地址
     */
    public int setAddr(int goodsId, String phone, String addr, int no) {
        // 检查格式
        if (!checkPhone(phone)) {
            return GameErrorCode.E_REAL_REWARD_PHONE_ERROR;
        }
        if (StringUtils.isNullOrEmpty(addr)) {
            return GameErrorCode.E_REAL_REWARD_NO_ADDR;
        }


        UserRealReward realReward = null;
        if (no > 0) {
            // 指定NO填写
            for (int i = userRealRewardList.size() - 1; i >= 0; i--) {
                UserRealReward tmp = userRealRewardList.get(i);
                if (tmp.getNo() == no) {
                    realReward = tmp;
                    break;
                }
            }
        } else {
            // 按最后获得的道具ID填写
            for (int i = userRealRewardList.size() - 1; i >= 0; i--) {
                UserRealReward tmp = userRealRewardList.get(i);
                if (tmp.getGoodsId() == goodsId) {
                    realReward = tmp;
                    break;
                }
            }
        }
        if (realReward == null) {
            return GameErrorCode.E_REAL_REWARD_NO_EXIST;
        }
        if (realReward.getAddrTime().getTime() != 0) {
            return GameErrorCode.E_REAL_REWARD_HAD_SET_ADDR;
        }

        // 填写地址
        realReward.setPhone(phone);
        realReward.setAddr(addr);
        realReward.setAddrTime(new Date());

        // 返回
        LuckyDrawProto.LuckyDrawSetAddrRespMsg.Builder builder = LuckyDrawProto.LuckyDrawSetAddrRespMsg.newBuilder();
        builder.setRet(0);
        builder.setRealRewardMsg(LuckyDrawPb.parseLuckyDrawRealRewardMsg(realReward));
        player.sendPacket(ClientProtocol.U_LUCKY_DRAW_SET_ADDR, builder);
        return 0;
    }

    // 检查手机号
    private boolean checkPhone(String phone) {
        return Pattern.matches("^1\\d{10}$", phone);
    }

    @Override
    public boolean loadData() {
        userRealRewardList = UserRealRewardBusiness.getUserRealRewardList(getUserId());
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public boolean saveData() {
        ArrayList<UserRealReward> newList = new ArrayList<>(userRealRewardList);
        for (UserRealReward data : newList) {
            if (data.isInsertOption()) {
                UserRealRewardBusiness.addUserRealReward(data);
            } else if (data.isUpdateOption()) {
                UserRealRewardBusiness.updateUserRealReward(data);
            }
        }
        return true;
    }
}
